// 权限控制

import router from '@/router'
import store from './store'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getUserInfo, getUserInfoDetail } from '@/api/user'

// 登陆页面权限控制
const white_list = ['/login', '/404']
router.beforeEach(async(to, from, next) => {
  const token = store.state.user.token
  NProgress.start()
  if (token) {
    if (to.path === '/login') {
      next('/')
      NProgress.done()
    } else {
      // 避免每次跳转页面重复请求接口
      if (!store.state.user.userInfo.userId) {
        const userInfo = await getUserInfo()
        const userInfoDetail = await getUserInfoDetail(userInfo.data.userId)
        store.commit('user/setUserInfo', { ...userInfo.data, ...userInfoDetail.data })
      }
      next()
    }
  } else {
    if (white_list.includes(to.path)) {
      next()
    } else {
      next('/login')
      NProgress.done()
    }
  }
})

router.afterEach((to, from) => {
  NProgress.done()
})
